package org.nf.trading.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

    public static final String DELAY_EXCHANGE_NAME = "delay.exchange";
    public static final String DELAY_QUEUE_NAME = "delay.queue";
    public static final String DELAY_ROUTER_KEY = "order.message";

    public static final String DIRECT_EXCHANGE_NAME = "direct.exchange";
    public static final String DIRECT_QUEUE_NAME = "direct.queue";
    public static final String DIRECT_ROUTER_KEY = "key.post";

    

    /**
     * 自定义Exchange，设置延迟交换机类型为direct，也可以设置为topic等其他类型
     */
    @Bean
    public CustomExchange delayExchange() {
        Map<String, Object> params = new HashMap<>();
        params.put("x-delayed-type", "direct");
        return new CustomExchange(DELAY_EXCHANGE_NAME, "x-delayed-message", false, true, params);
    }

    /**
     * 装配交换机
     */
    @Bean
    public DirectExchange exchange() {
        return new DirectExchange(DIRECT_EXCHANGE_NAME);
    }


    /**
     * 装配消息队列
     * Queue构造方法第二个参数表示是否持久化消息
     * @return
     */
    @Bean
    public Queue delayQueue(){
        return new Queue(DELAY_QUEUE_NAME, false);
    }

    /**
     * 装配队列
     * @return Queue
     */
    @Bean
    public Queue directQueue() {
        return new Queue(DIRECT_QUEUE_NAME, false);
    }

    /**
     * 将queue绑定到exchange
     */

    @Bean
    public Binding delayBinding(){
        return BindingBuilder
                .bind(delayQueue())
                .to(delayExchange())
                .with(DELAY_ROUTER_KEY)
                .noargs();
    }
    /**
     * 将队列绑定到交换机
     * @return Binding
     */
    @Bean
    public Binding directBinding() {
        return BindingBuilder
                .bind(directQueue())
                .to(exchange())
                .with(DIRECT_ROUTER_KEY);
    }

    /**
     * 自定义消息转换器
     * @return
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }
}
